package org.blogwu.learn.multithread.chapter3.demo6;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockTestV2 extends Thread {
    static ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
    static Lock readLock = readWriteLock.readLock();
    static Lock writeLock = readWriteLock.writeLock();

    static ReentrantLock reentrantLock = new ReentrantLock();

    public ReadWriteLockTestV2(String name) {
        super(name);
    }

    public static void readValue(Lock lock) {
        lock.lock();
        try {
            Thread.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void writeValue(Lock lock) {
        lock.lock();
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    @Override
    public void run() {
        long startTime = System.currentTimeMillis();
        // 读5次,写一次  循环10次
        for (int i = 0; i < 5; i++) {
            for (int j = 0; j < 5; j++) {
//                readValue(readLock);  //读写锁
                readValue(reentrantLock); //重入锁
            }
            for (int j = 0; j < 1; j++) {
//                writeValue(writeLock);//读写锁
                writeValue(reentrantLock);//重入锁
            }
        }
        System.out.println(getName() + " 线程执行完毕" + (System.currentTimeMillis() - startTime));
    }

    public static void main(String[] args) throws InterruptedException {
        long startTime = System.currentTimeMillis();
        Thread[] cz = new Thread[10];
        for (int i = 0; i < 10; i++) {
            cz[i] = new ReadWriteLockTestV2("线程" + i);
        }
        for (int i = 0; i < 10; i++) {
            cz[i].start();
        }
        for (int i = 0; i < 10; i++) {
            cz[i].join();
        }

        System.out.println("所有线程执行完毕" + (System.currentTimeMillis() - startTime));
    }
}
